package study.designpattern.singleton;

/**
 * 类含有自身的对象引用时，非静态和静态的区别
 * @author taowei20061122@163.com
 *
 */
public class TestNonStatic {
	
	private String name;
	//看起来有递归的味道
	//非静态
	//private TestNonStatic instance = new TestNonStatic("nonStatic");
	private TestNonStatic instance;
	
	private static TestNonStatic instance2 = new TestNonStatic("nonStatic");
	
	public TestNonStatic getInstance() {
		return instance2;
	}
	
	private TestNonStatic(String name) {
		//this.instance = instance2;
		this.name = name;
		
	}
	
	public static void main(String[] args) {
		//类含有自身的对象引用时，若为非static的，则此处创建TestSingleton对象时会循环调用构造方法，直至堆栈溢出java.lang.StackOverflowError
		TestNonStatic instance1 = new TestNonStatic("instance1");
		TestNonStatic instance2 = new TestNonStatic("instance2");
		System.out.println(instance1+" instance1.name="+instance1.name+" instance1.instance2="+instance1.instance2);
		System.out.println(instance2+" instance2.name="+instance2.name+" instance2.instance2="+instance2.instance2);
		
		System.out.println("instance1.instance="+instance1.instance);
		System.out.println("instance2.instance="+instance2.instance);
	}

}
